import {defineStore} from "pinia";
import {computed, ref} from "vue";
import {UserVO} from "@/model/account.js";
import {TokenVO} from "@/model/common.js";

/*
 * 若有 export const A = { a: 0 }，
 * 如果[与多文件无关]有多个 const a = ref(A)，
 * 则会共享同一个A对象。
 * 若只对对象顶层属性，使用浅拷贝：...obj可以将对象属性展开，
 * 若对象包含嵌套对象或数组，使用深拷贝：
 * 比如JSON.parse(JSON.stringify(LoginDTO))或者使用一个深拷贝工具库。
 *
 */
export const useLoginStorage = defineStore('loginStorage', () => {
    const userInfo = ref({...UserVO});
    userInfo.value.userId = '';
    userInfo.value.username = '';
    userInfo.value.role = 'user';
    const isLogin = ref(false);
    const tokenInfo = ref({...TokenVO});
    tokenInfo.value.tokenName = 'sa-token';
    tokenInfo.value.tokenValue = '';

    const getUserInfo = computed(() => {
        return userInfo.value;
    });
    const getIsLogin = computed(() => {
        return isLogin.value;
    });
    const getTokenInfo = computed(() => {
        return tokenInfo.value;
    });

    const setUserInfo = (userVO) => {
        if (userVO === null || userVO === undefined) return;
        // userInfo.value = userVO;
        userInfo.value.userId = userVO.userId;
        userInfo.value.username = userVO.username;
        userInfo.value.role = userVO.role;
    }
    const setIsLogin = (value) => {
        if (value === null || value === undefined) return;
        isLogin.value = value;
    }
    const setTokenInfo = (tokenVO) => {
        if (tokenVO === null || tokenVO === undefined) return;
        // tokenInfo.value = tokenVO;
        tokenInfo.value.tokenName = tokenVO.tokenName;
        tokenInfo.value.tokenValue = tokenVO.tokenValue;
    }

    //重置函数
    const $reset = () => {
        userInfo.value.userId = '';
        userInfo.value.username = '';
        // userInfo.value.password = '';
        userInfo.value.role = 'user';
        isLogin.value = false;
        tokenInfo.value.tokenName = 'sa-token';
        tokenInfo.value.tokenValue = '';
    }

    return {
        userInfo,
        isLogin,
        tokenInfo,

        getUserInfo,
        getIsLogin,
        getTokenInfo,

        setUserInfo,
        setIsLogin,
        setTokenInfo,

        $reset,
    }
}, {
    /**
     * 相当于：
     * persist: {
     *      storage: localStorage,
     *      key: 'loginStorage',
     *      pick:['state1','state2','state3',...],
     *  }
     * */
    persist: true, // 启用持久化，默认存储在localStorage中，键名为store的id，持久化全部字段

});



